package com.yc.javaee.servlet.d0617;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "GetUploadServlet", value = "/upload/*")
public class GetUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // response.setContentType("text/html;charset=utf-8");
        // PrintWriter out = response.getWriter();
        // /C122_S2_Ply_JavaEE_war/upload/1.jpg
        //out.printf(request.getRequestURI() + "<br>");
        // /upload
        //out.printf(request.getServletPath() + "<br>");
        // /C122_S2_Ply_JavaEE_war
        //out.printf(request.getContextPath() + "<br>");
        // /upload/1.jpg
        String path = request.getRequestURI().replace(request.getContextPath(),"");
        // 1.jpg
        String file = path.replace("/upload/", "");
        String diskPath = "D:\\_文件柜\\112\\0617\\upload\\" + file;
        // 根据文件后缀 构建 contentType jpg, mp4
        String contentType = getServletContext().getMimeType(diskPath);
        // 设置响应类型
        response.setContentType(contentType);
        // 获取输出流
        ServletOutputStream out = response.getOutputStream();
        try(FileInputStream fis = new FileInputStream(diskPath)){
            byte[] bytes = new byte[1024];
            int count;
            while( (count = fis.read(bytes)) > 0){
                out.write(bytes,0,count);
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
